package com.woniu.zsd.recycle.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.recycle.mapper.RecyclingOrderMapper;
import com.woniu.zsd.recycle.model.RecyclingOrder;
import com.woniu.zsd.recycle.param.DataParam;
import com.woniu.zsd.recycle.service.MqttGateway;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class AllocationStationConsumer {
    @Resource
    private RecyclingOrderMapper recyclingOrderMapper;
    @Resource
    private MqttGateway mqttGateway;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(name = "allocation_station_queue"),
            exchange = @Exchange(name = "d2"),
            key = "allocation_station"
    ))
    @RabbitHandler
    public void allocationStation(String jsonStr) throws Exception {
        // 生成锁的键（基于订单号）
        System.out.println("收到分配站点的消息：" + jsonStr);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        DataParam dataParam = objectMapper.readValue(jsonStr, DataParam.class);
        System.out.println("........ccccccc............");
        String lockKey = "lock:allocation_station:" + dataParam.getRecyclingOrderNum();
        // 尝试加锁（设置过期时间防止死锁）
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 30, TimeUnit.SECONDS);

        if (locked != null && locked) {
            try {
                System.out.println("bbbbbbbbbbbbbb");
                System.out.println("订单编号"+dataParam.getRecyclingOrderNum());
                String recyclingOrderNum = dataParam.getRecyclingOrderNum();
                List<Integer> data = dataParam.getData();
                QueryWrapper<RecyclingOrder> wrapper = new QueryWrapper<>();
                wrapper.eq("recycling_order_num", recyclingOrderNum);
                RecyclingOrder recyclingOrder = recyclingOrderMapper.selectOne(wrapper);
                //站点接单了不再分配
                if (recyclingOrder.getStatus() == 2){
                    return;
                }

                //分配次数加1
                dataParam.setT(dataParam.getT()+1);
                //分配次数大于5次，不再分配
                if (dataParam.getT()==5){
                    recyclingOrder.setStationId(0);
                    recyclingOrderMapper.updateById(recyclingOrder);
                    return;
                }
                //分配站点,data为空即附近没有站点，不再分配
                if (data.get(dataParam.getT())==null){
                    recyclingOrder.setStationId(0);
                    recyclingOrderMapper.updateById(recyclingOrder);
                    return;
                }
                System.out.println("站点的id为："+data.get(dataParam.getT()));
                recyclingOrder.setStationId(data.get(dataParam.getT()));
                String Str = JSONUtil.toJsonStr(dataParam);
                recyclingOrderMapper.updateById(recyclingOrder);
                mqttGateway.sendToMqtt("station","收到新订单id:"+recyclingOrderNum);
                rabbitTemplate.convertAndSend("","waiting_allocation_station_queue",Str);
            } finally {
                // 释放锁
                redisTemplate.delete(lockKey);
            }
        } else {
            // 未获取到锁，可以选择重试或直接丢弃
            System.out.println("未能获取锁，订单号：" + dataParam.getRecyclingOrderNum());
        }

    }
}
